# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QVBoxLayout

from components import GridLayout
from server.api import BirdAPI
from ..base import BaseInterface, NullDataWidget, WallpaperCard


class BirdInterface(BaseInterface):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.currentPage = 1
        self.totalPage = 100
        self.keyword = ''
        self.verticalLayout = QVBoxLayout(self.view)
        self.gridLayout = GridLayout()
        self.nullDataWidget = NullDataWidget(self.view)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addLayout(self.gridLayout, 1)
        self.verticalLayout.addWidget(self.nullDataWidget, 0, Qt.AlignmentFlag.AlignBottom)

        self.nullDataWidget.hide()

    def loadData(self, keyword: str = None):
        if keyword is None:
            keyword = self.keyword
        else:
            self.keyword = keyword
        self.load(BirdAPI.search, keyword, page=self.currentPage, slot=self.onSearchResult)

    def onSearchResult(self, result: dict):
        data = result['data']
        dataList = data['list']
        self.totalPage = data['total_page']
        if not dataList:
            if self.currentPage <= 1:
                self.nullDataWidget.setText('没有找到相关的壁纸')
            self.nullDataWidget.show()
            self.gridLayout.update()
            return
        for item in dataList:
            url = item['url']
            tag = item['tag']
            label = self.addLabel(url, self.gridLayout)
            label.setTitle(tag)
            label.setMaxUrl(url)
        self.lazyTimerStart()

    def nextPage(self):
        if self.currentPage >= self.totalPage:
            self.nullDataWidget.setText('没有更多的壁纸了')
            self.nullDataWidget.show()
            return
        self.currentPage += 1
        self.loadData()

    def onReload(self):
        self.clear()
        self.verticalScrollBar().setValue(0)
        self.currentPage = 1
        self.loadData()

    def clear(self):
        self.gridLayout.takeAllWidgets()

    def onLabelFinished(self, label: WallpaperCard):
        if label.isNull():
            return
        image = label.image
        image = image.scaledToWidth(300, Qt.TransformationMode.SmoothTransformation)
        label.setMinimumSize(image.size())
